//房源panal
var gridStoreJingJ = null;
Ext.define('customer.signed.add.estatePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var me=this;
		var row_1={
				id:"isPaydepositTrue",
				fieldDefaults: {
			            labelAlign: 'top',
			            msgTarget: 'side'
			    },
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
			    border: false,
				layout: 'hbox',
				items: [{
		            items: [{
		            	xtype:'container',
		            	layout:'hbox',
		            	border:true,
		            	items:[
							{
							    xtype:'textfield',
							    name: 'signedId',
							    id: 'signedId',
							    hidden: true,
							    readOnly:true,
							    value: signedInfoObj.id
							},
		            		{xtype: "textfield", id: "projectId", name: "projectId", hidden: true},
		            		{
		            		xtype:'textfield',
			                fieldLabel: '房号',
			                name: 'combinedName',
			                readOnly:true
			                },{
			                	xtype:'button',
			                	text:'选择房源',
			                	margin: 5,
			                	iconCls:'icon-search', 
			                	id:'changeHouse',
			           		    handler: function() {
			           		 	    var selectWindow=Ext.create('component.estate.selectWindow',{
			           		 	        callbackFun: function (record) {
			           		 	      //设置折扣信息
			          	        		  //从房源信息里面获取
			          	        		  var result= Ext.JSON.decode(record);;
			          	        	    var form=me.getForm();
			           		 	          form.setValues(result);
			           		 	          //获取房间业态，以便获取收款周期
				           		 	      loadRoomType(result.id, result.projectId);
			          	        		  //折前单价  折前总价 折扣金额  折扣比例 折扣说明 签约单价 合同金额 认筹金额 认购金额 经济人
			          	        		  var values={};
			          	        		  values.discountAfterPrice=result.discountAfterPrice;
			          	        		  values.floorType=result.floorType;
			          	        		  //折前单价
			          	        		  values.calculateUnitPrice=result.calculateUnitPrice;
			          	        		  //折前总价 
			          	        		  values.totalPrice=result.totalPrice;
			          	        		  //折扣金额
			          	        		  if(result.discountAfterPrice!=null){
			          	        			  values.discountAfterAmount=result.totalPrice-result.discountAfterPrice;
			          	        		  }
			          	        		  //折扣比例
			          	        		  if(result.floorType=="1"){
			          	        			  values.discountRate=result.discountRate;
			          	        		  }else if(result.floorType=="0"){
			          	        			  values.discountRate=0;
			          	        		  }
			          	        		  values.discountRateHidden=result.discountRate;
			          	        		  //签约单价
			          	        		  values.discountAmount=result.discountAmount;
			          	        		  //合同金额
			          	        		  values.discountTotalAmount=result.discountTotalAmount;
			          	        		  //已收总金额
			          	        		  values.contractAmountName=contractAmountName;
			          	        		  //未收总金额
			          	        		  values.totalNeedReceivedAmount=result.discountTotalAmount-totalHaveReceivedAmount;
			           		 	          values.hetongPayPrice = totalHaveReceivedAmount;
			           		 	          var subscribeInfoForm=Ext.getCmp("subscribeInfoForm").getForm();
			           		 	          subscribeInfoForm.setValues(values);
			           		 	          subscribeInfoForm.findField("isCalculate").setValue("1"); 
			           		 	          if(result.floorType=="0"){
			          	        			  subscribeInfoForm.findField("discountAfterAmount").setReadOnly(true);
			          	        		  }else if(result.floorType=="1"){
			          	        			  subscribeInfoForm.findField("discountAfterPrice").setVisible(false);
			          	        		  }
			           		 	        },
			           		 	        rStatus: '1',
	           		 	                customerId:customerId
			           		 	    });
			           		 	    selectWindow.show();
			        		    }
			                }]
		                
		            }, {
		                xtype:'textfield',
		                fieldLabel: '建筑面积(㎡)',
		                anchor: '80%',
		                name: 'buildingArea',
		                readOnly:true
		            }, {
		                xtype:'textfield',
		                fieldLabel: '分摊面积(㎡)',
		                anchor: '80%',
		                name: 'sharingArea',
		                readOnly:true
		            }, {
		                xtype:'textfield',
		                fieldLabel: '折前单价(元)',
		                anchor: '80%',
		                name: 'calculateUnitPrice',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '房源ID',
		                name: 'id',
		                readOnly:true,
		                hidden:true
		            }]
		        }, {
		            items: [{
		                xtype:'textfield',
		                fieldLabel: '房源状态',
		                anchor: '80%',
		                name: 'roomStatusName',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '套内面积(㎡)',
		                anchor: '80%',
		                name: 'innerArea',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '计价面积(㎡)',
		                anchor: '80%',
		                name: 'billingArea',
		                id:'billingArea',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: '折前总价(元)',
		                anchor: '80%',
		                name: 'totalPrice',
		                readOnly:true
		            }]
		        }]
	    };
		var items=[row_1];
		var initConfigg = {
				title:"房产信息",
				id:'estatePanel',
				bodyStyle: 'padding:5px 5px 0',
		        minHeight: 200,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});

Ext.define('customer.signed.add.customerPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var me=this;
		var documentTypeStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'name'],
		    data :documentType
		});
		var row_1={
				fieldDefaults: {
			            labelAlign: 'top',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [{
		            	xtype:'container',
		            	layout:'hbox',
		            	anchor: '80%',
		            	items:[{
		            		xtype:'textfield',
			                fieldLabel: '客户姓名',
			                anchor: '80%',
			                name: 'customerName',
			                readOnly:true,
			                allowBlank:false
			                },{
			                	xtype:'button',
			                	text:'选择客户',
			                	margin: 5,
			                	hidden:showChooseCustomer,
			                	iconCls:'icon-search', 
			                	id:'changeCustomerBtn',
			           		    handler: function() {
			           		    	/*var projectId = Ext.getCmp("projectId").getValue();*/
			           		    	var projectId ="";
			           		    	if(customerProjectId!="" && null!=customerProjectId){
			           		    		projectId=customerProjectId;
			           		    	}else{
			           		    		projectId = Ext.getCmp("projectId").getValue();
			           		    	}
			           		 	    var selectWindow=Ext.create('component.customer.selectWindow',{
			           		 			callbackFun: function (record) {
				           		 	  		var result=Ext.JSON.decode(record);
//				           		 	   		Ext.getCmp('userName').setValue("");
//			           		 	          	Ext.getCmp('userName').setValue(result.userId);
			           		 	          	userIdStore.load({
				           		 	   			params:{
													'projectId':result.projectId
				           		 	        	},
			           		 	        	  	callback:function(){
			           		 	        	  		var index = userIdStore.find('id',userId);  
							                        if(index!=-1){  
							                            var record  = new Record({
							                            	relationAgentid:userId,
							                            	proportionCommission:'100'
							                            }); 
							                            gridStoreJingJ.removeAll();
							                            gridStoreJingJ.insert(0, record);
							                            var dealCategory = Ext.getCmp("dealCategory").getValue();
							                            if("3" == dealCategory || "2" == dealCategory){
							                            	Ext.getCmp("proportionCommission").setVisible(true);
							                            }else{
							                            	Ext.getCmp("proportionCommission").setVisible(false);
							                            }
							                        }
			           		 	        	  	}
				           		 	    	});
			           		 	          	var form=me.getForm();
			           		 	          	form.setValues(result);
				           		 	       	var extraParams=gridStore.getProxy().extraParams;
				           		 	     	extraParams.customerId=Ext.getCmp('customerId').getValue();
				           		 	     	extraParams.memberType=1;
				           		 	      	gridStore.load();
					           		 	    if(gridStore.getCount()>=4){
					    				    	Ext.getCmp("insertBtn").setVisible(false);
					    				    }
					    				    customerId=extraParams.customerId;
			           		 	        },
			           		 	        projectId: projectId,
			           		 	        resourcesCode:'menu_0006_0001'
			           		 	    });
			           		 	    selectWindow.show();
			        		    }
			                }]
		                
		            }, {
		                xtype:'combobox',
		                fieldLabel: '<font style="color: #e90000;">*</font>证件类型',
		                anchor: '80%',
		                name: 'peDocumentTypeName',
		                store: documentTypeStore,
					    queryMode: 'local',
					    typeAhead: true,
					    displayField: 'name',
					    valueField: 'value',
					    allowBlank: false,
					    blankText: "客户信息证件类型不能为空"
		            }, {
		                xtype:'textfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>证件号码',
		                anchor: '80%',
		                name: 'peDocumentNumber',
		                allowBlank: false,
		                blankText: "客户信息证件号码不能为空"
		            }, {
		                xtype:'textfield',
		                fieldLabel: '<font style=\"color: #e90000;\">*</font>联系电话',
		                anchor: '80%',
		                name: 'customerPhone',
		                readOnly:true
		            }]
		        }, {
		            items: [{
		                xtype:'textfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>邮寄地址',
		                anchor: '80%',
		                name: 'peContactAddress',
		                allowBlank: false,
		                blankText: "邮寄地址不能为空"
		            },{
		                xtype:'textfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>邮编',
		                anchor: '80%',
		                name: 'pePostcode',
		                allowBlank: false,
		                blankText: "邮编不能为空"
		            },{
		                xtype:'textfield',
		                fieldLabel: '客户来源',
		                anchor: '80%',
		                name: 'customerOriginName',
		                readOnly:true
		            },{
		                xtype:'textfield',
		                fieldLabel: 'ID',
		                anchor: '80%',
		                name: 'id',
		                id:'customerId',
		                readOnly:true,
		                hidden:true
		            }]
		        }]
	    };
		
		var gridStore = Ext.create('Ext.data.Store', {
			id:'familyMemberGridStore',
		    fields: ["memberName","documentType","documentNumber","mobile"],
		    //是否在服务端排序 （true的话，在客户端就不能排序）
		    remoteSort: false,
		    proxy: {
		        type: 'ajax',
		        url: contextPath+'/customer/familyMember/findList',
		        reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        },
		        actionMethods: {read: 'POST'}
		    }
		});
		var columns = [{
			text : "姓名",
			dataIndex : 'memberName',
			width:'20%',
			editor: {
                xtype: 'textfield'
            }
		}, {
			text : "证件类型",
			dataIndex : 'documentType',
			width:'20%',
			editor: new Ext.form.field.ComboBox({
			    store: documentTypeStore,
			    queryMode: 'local',
			    displayField: 'name',
			    valueField: 'value'
            }),
            renderer: function(value,metadata,record){  
                var index = documentTypeStore.find('value',value);  
                if(index!=-1){  
                    return documentTypeStore.getAt(index).data.name;  
                }  
                return value;  
            }
		}, {
			text : "证件号码",
			dataIndex : 'documentNumber',
			width:'20%',
			editor: {
                xtype: 'textfield',
                maxLength:18
            }
		},{
			text : "手机号码",
			dataIndex : 'mobile',
			width:'20%',
			editor: {
                xtype: 'textfield'
            }
		},{
        	text:'操作',
        	xtype : 'actioncolumn',
        	items:[{
        		 iconCls:'icon-delete',
        		 tooltip: '删除', 
        		 handler: function(grid, rowIndex, colIndex) {
        			 gridStore.removeAt(rowIndex);
        			  if(gridStore.getCount()<4){
  				    	Ext.getCmp("insertBtn").setVisible(true);
  				    	Ext.getCmp("customerSelectBtn").setVisible(true);
  				    }
        		 }
        	}]
        }];
		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		var row_2=Ext.create('Ext.grid.Panel', {
			id:'familyMemberGridPanel',
			region : 'south',
			title:"共同购房者",
			minHeight:200,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore,
			columns : columns,
			plugins: [cellEditing],
			tbar:[{text:'新增',iconCls:'icon-add',id:'insertBtn',
				handler:function(){
				    Ext.define('Record', { 
			            extend: 'Ext.data.Model' 
				    }); 
				    var record  = new Record(); 
				    gridStore.insert(0, record);
				    cellEditing.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
				    if(gridStore.getCount()>=4){
				    	Ext.getCmp("insertBtn").setVisible(false);
				    	Ext.getCmp("customerSelectBtn").setVisible(false);
				    }
			}
			},{
            	xtype:'button',
            	text:'选择客户',
            	margin: 5,
            	iconCls:'icon-search',
            	id:'customerSelectBtn',
       		    handler: function() {
       		    	var projectId = Ext.getCmp("projectId").getValue();
       		    	
       		 	    var selectWindow=Ext.create('component.customer.selectWindow',{
       		 			callbackFun: function (record) {
   		 	          		var result=Ext.JSON.decode(record);
   		 	          		
		           		 	Ext.define('Record', { 
					            extend: 'Ext.data.Model',
					            fields: ["memberName","documentType","mobile","documentNumber"]
						    }); 
						    var record  = new Record({
						    	 memberName:result.customerName,
						    	 documentType:result.peDocumentType,
						    	 mobile:result.customerPhone,
						    	 documentNumber:result.peDocumentNumber
						    }); 
						    gridStore.insert(0, record);
						    
						    if(gridStore.getCount()>=4){
						    	Ext.getCmp("insertBtn").setVisible(false);
						    	Ext.getCmp("customerSelectBtn").setVisible(false);
						    	return;
						    }
						    
       		 	        },
       		 	        projectId: projectId,
       		 	        resourcesCode:'menu_0006_0001'
       		 	    });
       		 	    selectWindow.show();
    		    }
			}
			]
		});
		var items=[row_1,row_2];
		var initConfigg = {
		        title:"客户信息",
		        id:'customerPanel',
		        minHeight:320,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
	}
});
Ext.define('customer.signed.add.subscribePanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var me=this;
		var contactTypesStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'name'],
		    data:contactTypes
		});
		
		
		var row_1={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [ {
		                xtype:'textfield',
		                fieldLabel: '合同编号',
		                name:'signedCode',
		                value: signedInfoObj.signCode
		            },{
		                xtype:'displayfield',
		                fieldLabel: '折前单价(元)',
		                name:'calculateUnitPrice'
		            }]
		        }, {
		            items: [{
		                xtype: 'combobox',
		                fieldLabel: '合同类型',
		                name:'contactType',
		                store: contactTypesStore,
		                queryMode: 'local',
		                displayField: 'name',
		                valueField: 'value',
		                value: signedInfoObj.contactType
		            },{
		                xtype:'displayfield',
		                fieldLabel: '折前总价(元)',
		                name: 'totalPrice'
		            }]
		        }]
	    };
		
		var calculationFloor = function(){
			var subscribeForm =  me.getForm();
			var subscribe=me.getForm().getValues();	
			var calculationAmount = subscribe['discountAfterPrice'];
			var totalPrice=subscribeForm.findField("totalPrice").getValue();
			if(!totalPrice)return;
			if(calculationAmount==null||calculationAmount==""){
				calculationAmount=totalPrice;
			}
			var newdiscountAfterAmount = totalPrice-calculationAmount;
			subscribeForm.findField('discountAfterAmount').setValue(newdiscountAfterAmount);
		}
		
		var calculationDiscount=function(){
			var subscribe=me.getForm().getValues();
			var billingArea = Ext.getCmp("billingArea").getValue();
			//折前单价
			var calculateUnitPrice=me.getForm().findField("calculateUnitPrice").getValue();
			if(!calculateUnitPrice)return;
			//折前总价
			var totalPrice=me.getForm().findField("totalPrice").getValue();
			if(!totalPrice)return;
			//折扣金额
			var discountAfterAmount=me.getForm().findField("discountAfterAmount").getValue();
			//当前折扣
			var nowDiscountRate=(100-((discountAfterAmount/totalPrice)*100)).toFixed(2);
			var nowTotalPrice=totalPrice-discountAfterAmount;
			var nowUnitPrice = (nowTotalPrice/billingArea).toFixed(2);
			//首付分期金额
			var decorationMoneyAmount = me.getForm().findField("decorationMoneyAmount").getValue();
			//折后比例 = 折扣金额/折前总价
			//合同金额=  折前总价 - 折扣金额
			//签约单价 =  合同金额/计价面积
			//合同未收金额 = 合同金额-已收金额
			var reAmount = nowTotalPrice-totalAmount;
			me.getForm().findField("totalNeedReceivedAmount").setValue(accAdd(reAmount, decorationMoneyAmount));
			me.getForm().findField("discountRate").setValue(parseInt(nowDiscountRate, 0));
			me.getForm().findField("discountAmount").setValue(Math.round(nowUnitPrice));
			me.getForm().findField("discountTotalAmount").setValue(accAdd(nowTotalPrice, decorationMoneyAmount));
			me.getForm().findField("discountAfterAmount").setValue(Math.round(discountAfterAmount));
			me.getForm().findField("roomTotalAmount").setValue(nowTotalPrice);
		};
		
		var calculationByRate = function(discountRate){
			var subscribe=me.getForm().getValues();
			var floorType = me.getForm().findField("floorType").getValue();
			
			//折前总价
			var totalPrice=me.getForm().findField("totalPrice").getValue();
			if(!totalPrice)return;
			var discountAfterPrice = me.getForm().findField("discountAfterPrice").getValue();
			//0: 折后总价 1: 折扣比率
			if(1 == floorType){
				var billingArea = Ext.getCmp("billingArea").getValue();
				//折前单价
				var calculateUnitPrice=me.getForm().findField("calculateUnitPrice").getValue();
				if(!calculateUnitPrice)return;
				
				//折后总价 = 折扣比例 * 合同金额
				var discountAfterPrice = totalPrice * discountRate/100;
				me.getForm().findField("discountAfterPrice").setValue(Math.round(discountAfterPrice));
			}else if(0 == floorType){
				me.getForm().findField("discountAfterAmount").setValue(totalPrice - discountAfterPrice);
			}
		};
		
		var row_2={
				fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side'
		        },
		        collapsible: true,
		        //collapsed: true,
				xtype: 'fieldset',
                title:'折扣信息',
                //layout: 'anchor',
                defaultType: 'textfield',
                items:[
                 {
                		xtype: 'numberfield',
                    	fieldLabel: '折后总价(元)',
                    	minValue: 0,
                    	id:'discountAfterPrice',
                    	name:'discountAfterPrice',
                    	hideTrigger:true,
                    	value: signedInfoObj.signAmount,
                    	listeners:{
                    		change:function(){
                    			calculationFloor();
                    		}
                    	}
                 },{
                	xtype: 'numberfield',
                	fieldLabel: '折扣金额(元)',
                    name: 'discountAfterAmount',
                    hideTrigger:true,
                    minValue: 0,
                    value: signedInfoObj.discountAfterAmount,
                    readOnly: true,
                    listeners: {
	                    change: function(field, value) {
	                        calculationDiscount();
	                    }
	                }
                },{
	            	xtype:'container',
	            	layout:'hbox',
	            	anchor: '80%',
	            	items:[{
	            		xtype: 'numberfield',
		                fieldLabel:'折扣比例(%)',
		                name:'discountRate',
		                hideTrigger:true,
	                    minValue: 0,
	                    maxValue: 100,
	                	value: signedInfoObj.discountRate,
		                listeners: {
		                    change: function(field, value) {
		                        //calculationByRate(value);
		                    }
		                }
		                
	            	},{
	            		xtype:'displayfield',
	            		hideLabel:true,
	            		name:'discountRateDisplay'
	            	},{
	            		xtype: 'hiddenfield',
		                name:'discountRateHidden'
	            	},{
	            		xtype: 'hiddenfield',
		                name:'isCalculate'
	            	},{
	            		name:'floorType',
	            		xtype: 'hiddenfield'
	            	}]
	                
	            },{
                	xtype: 'textareafield',
                	fieldLabel: '折扣说明',
                	anchor: '50%',
                    name: 'discountNote',
                    value: signedInfoObj.discountNote
                }]
	    };
		
		var row_3={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [{
		                xtype:'displayfield',
		                fieldLabel: '签约单价(元)',
		                name: 'discountAmount',
		                readOnly:true,
		                renderer: Ext.util.Format.numberRenderer('0,000')
		            }]
		        }, {
		            items: [{
		            	xtype: 'displayfield',
		                fieldLabel: '<font style="color: #e90000;">*</font>合同总金额(元)',
		                name:'discountTotalAmount',
		                id:'discountTotalAmount',
		                readOnly:true,
		                renderer: Ext.util.Format.numberRenderer('0,000')
		            }]
		        }, {
		            items: [{
		            	xtype: 'displayfield',
		                fieldLabel: '房款金额(元)',
		                name:'roomTotalAmount',
		                id:'roomTotalAmount',
		                readOnly:true,
		                renderer: Ext.util.Format.numberRenderer('0,000.00')
		            }]
		        }, {
		        	items:[{
		        		xtype: 'hiddenfield',
		                name:'hetongPayPrice'
		        	}]
		        }]
	    };
		var dealCategoryStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'text'],
		    data : [
                //{"value":"1", "text":"推荐成交"},
		        {"value":"2", "text":"单独成交"},
		        {"value":"3", "text":"共同成交"}
		    ]
		});
		var row_4={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
					items: [{
		            	xtype: 'displayfield',
		                fieldLabel: '已收认购金额(元)',
		                name:'haveReceivedPayDepositAmount',
		                value:haveReceivedPayDepositAmount
		            }]
		        }, {
		        	items: [{
		            	xtype: 'displayfield',
		                fieldLabel: '合同未收金额(元)',
		                name:'totalNeedReceivedAmount',
		                id:'totalNeedReceivedAmount',
		                labelWidth:100,
		          		renderer: Ext.util.Format.numberRenderer('0,000.00')
		            }]
		        }, {
		        	items: [{
		            	xtype: 'displayfield',
		                fieldLabel: '首付分期金额(元)',
		                name:'decorationMoneyAmount',
		                id:'decorationMoneyAmount',
		                labelWidth:100,
		          		renderer: Ext.util.Format.numberRenderer('0,000.00')
		            }]
		        }, {
		        	items:[{
		        		xtype: 'hiddenfield',
		                name:''
		        	}]
		        }]
	    };
		//删除装修金额
		var totalDecorationMoneyAmount = function(){
			var decorationMoneyAmount = Ext.getCmp("decorationMoneyAmount"); //首付分期
    		var discountTotalAmount = Ext.getCmp("discountTotalAmount"); //合同金额
    		discountTotalAmount.setValue(discountTotalAmount.getValue() - decorationMoneyAmount.getValue());
    		var totalNeedReceivedAmount = Ext.getCmp("totalNeedReceivedAmount"); //未收金额
    		totalNeedReceivedAmount.setValue(totalNeedReceivedAmount.getValue() - decorationMoneyAmount.getValue());
    		decorationMoneyAmount.setValue(0);
		};
		var row_5={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				items: [{
		            items: [{
		                xtype:'displayfield',
		                fieldLabel: '合同已收金额(元)',
		                name: 'contractAmountName',
		                id:'contractAmountName',
		                labelWidth:100
		                //renderer: Ext.util.Format.numberRenderer('0,000')
		            }]
		        }, {
		            items: [{
		            	xtype: "checkboxgroup",
						id:"decorationMoney",
						name :"decorationMoney",
						items:[{
					    		boxLabel:'首付分期',
					    		id:'1'
					    }],
					    listeners: {
					    	change: function(field,value) {
					    		var checked = field.getChecked();
					    		if(checked.length == 1){
									var record_1  = new needReceiveRecord({
										receivablesFunds:'一期款(首付分期)',
										businessFlag:'19',
										housingFundType:'29',
										receivedAmount:0
									});
									var record_2  = new needReceiveRecord({
										receivablesFunds:'二期款(首付分期)',
										businessFlag:'19',
										housingFundType:'30',
										receivedAmount:0
									});
									var record_3  = new needReceiveRecord({
										receivablesFunds:'三期款(首付分期)',
										businessFlag:'19',
										housingFundType:'31',
										receivedAmount:0
									});
									var record_4  = new needReceiveRecord({
										receivablesFunds:'四期款(首付分期)',
										businessFlag:'19',
										housingFundType:'32',
										receivedAmount:0
									});
									var record_5  = new needReceiveRecord({
										receivablesFunds:'五期款(首付分期)',
										businessFlag:'19',
										housingFundType:'33',
										receivedAmount:0
									});
									gridStore.add(record_1);
									gridStore.add(record_2);
									gridStore.add(record_3);
									gridStore.add(record_4);
									gridStore.add(record_5);
					    		}else{
									//取消首付分期
									//1、删除首付分期金额
									totalDecorationMoneyAmount();
									//2、将内容赋值给临时对象
									gridStore.each(function(record) {
										if(record.get('receivablesFunds').indexOf('首付分期') < 0){
											gridStoreTemporary.add(record);
										}
									});
									//3、删除原对象内容
									gridStore.removeAll();
									//4、将临时对象的内容还原给原对象
									gridStoreTemporary.each(function(record) {
										gridStore.add(record);
									});
									//5、清空临时对象
									gridStoreTemporary.removeAll();
					    		}
					    	}
					    }
		            }]
		        }, {
		        	items:[{
		        		xtype: 'hiddenfield',
		                name:''
		        	}]
		        }, {
		        	items:[{
		        		xtype: 'hiddenfield',
		                name:''
		        	}]
		        }]
	    };
		var paymentMethodsStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'name'],
		    data :paymentMethods
		});
		
		var decorationMoneyList = [
			{"value":"0","name":"无首付分期"},
            {"value":"1","name":"一次性付款"},
            {"value":"2","name":"分期付款"},
            {"value":"3","name":"商业按揭"}
        ];
		var decorationMoneyStore = Ext.create('Ext.data.Store', {
		    fields: ['value', 'name'],
		    data :decorationMoneyList
		});
		
		var row_6={
				fieldDefaults: {
			            labelAlign: 'left',
			            msgTarget: 'side'
			    },
			    border: false,
			    defaults: {
			            border: false,
			            xtype: 'panel',
			            flex: 1,
			            layout: 'anchor'
			    },
				layout: 'hbox',
				anchor:'50%',
				items: [{
		            items: [{
		            	xtype: 'combobox',
		                fieldLabel: '<font style="color: #e90000;">*</font>支付方式',
		                name:'paymentMethod',
		                id:'paymentMethod',
		                store: paymentMethodsStore,
		                queryMode: 'local',
		                displayField: 'name',
		                valueField: 'value',
		                value: signedInfoObj.paymentMethod,
		                listeners: {
		                    change: function(field,value) {
		                    	//由于没有找到效率高的解决方案
		                    	//（①全部删除对用户体验不好；②循环删除会下标越界；③js中对象之间的赋值是值引用；）
		                    	//因此暂时用以下方法处理删除合同金的功能
		                    	//1、将内容赋值给临时对象
				    			gridStore.each(function(record) {   
				    			    if(record.get('receivablesFunds').indexOf('首付分期') >= 0){
				    			    	gridStoreTemporary.add(record);
				    			    }  
				    			});  
				    			//2、删除原对象内容
				    			gridStore.removeAll();
				    			//3、生成合同金应收款数据
		                        if(value=="1"){ 
		                        	//一次性付款 
		                        	var record  = new needReceiveRecord({
		                        		receivablesFunds:field.getRawValue(),
		                        		businessFlag:'9',
		                        		housingFundType:'5',
		                        		receivedAmount:objectAmount[0].total
		                        	});
		                        
		        				    gridStore.add(record);
		                        }else if(value=="2"){
		                        	//分期付款
		                        	var record_1  = new needReceiveRecord({
		                        		receivablesFunds:'一期款',
		                        		businessFlag:'9',
		                        		housingFundType:'12',
		                        		receivedAmount:objectAmount[0].total
		                        	});
		                        	var record_2  = new needReceiveRecord({
		                        		receivablesFunds:'二期款',
		                        		businessFlag:'9',
		                        		housingFundType:'13',
		                        		receivedAmount:0
		                        	});
		                        	var record_3  = new needReceiveRecord({
		                        		receivablesFunds:'三期款',
		                        		businessFlag:'9',
		                        		housingFundType:'14',
		                        		receivedAmount:0
		                        	});
		                        	var record_4  = new needReceiveRecord({
		                        		receivablesFunds:'四期款',
		                        		businessFlag:'9',
		                        		housingFundType:'15',
		                        		receivedAmount:0
		                        	});
		                        	var record_5  = new needReceiveRecord({
		                        		receivablesFunds:'五期款',
		                        		businessFlag:'9',
		                        		housingFundType:'16',
		                        		receivedAmount:0
		                        	});
		                        	gridStore.add(record_1);
		                        	gridStore.add(record_2);
		                        	gridStore.add(record_3);
		                        	gridStore.add(record_4);
		                        	gridStore.add(record_5);
		                        }else if(value=="3"){
		                        	//商业按揭
		                        	var record_1  = new needReceiveRecord({
		                        		receivablesFunds:'首付款',
		                        		businessFlag:'9',
		                        		housingFundType:'6',
		                        		receivedAmount:objectAmount[0].total
		                        	});
		                        	var record_2  = new needReceiveRecord({
		                        		receivablesFunds:'银行按揭',
		                        		businessFlag:'9',
		                        		housingFundType:'7',
		                        		receivedAmount:0
		                        	});
		                        	gridStore.add(record_1);
		                        	gridStore.add(record_2);
		                        }else if(value=="4"){
		                        	//公积金按揭
		                        	var record_1  = new needReceiveRecord({
		                        		receivablesFunds:'首付款',
		                        		businessFlag:'9',
		                        		housingFundType:'10',
		                        		receivedAmount:objectAmount[0].total
		                        		
		                        	});
		                        	var record_2  = new needReceiveRecord({
		                        		receivablesFunds:'公积金',
		                        		businessFlag:'9',
		                        		housingFundType:'11',
		                        		receivedAmount:0
		                        	});
		                        	gridStore.add(record_1);
		                        	gridStore.add(record_2);
		                        }else if(value=="5"){
		                        	//组合贷款
		                        	var record_1  = new needReceiveRecord({
		                        		receivablesFunds:'首付款',
		                        		businessFlag:'9',
		                        		housingFundType:'17',
		                        		receivedAmount:objectAmount[0].total
		                        	});
		                        	var record_2  = new needReceiveRecord({
		                        		receivablesFunds:'银行按揭',
		                        		businessFlag:'9',
		                        		housingFundType:'18',
		                        		receivedAmount:0
		                        	});
		                        	var record_3  = new needReceiveRecord({
		                        		receivablesFunds:'公积金',
		                        		businessFlag:'9',
		                        		housingFundType:'19',
		                        		receivedAmount:0
		                        	});
		                        	gridStore.add(record_1);
		                        	gridStore.add(record_2);
		                        	gridStore.add(record_3);
		                        }else  if(value=="6"){
									//车位一次性付款
									var record  = new needReceiveRecord({
										receivablesFunds:field.getRawValue(),
										businessFlag:'9',
										housingFundType:'43',
										receivedAmount:objectAmount[0].total
									});

									gridStore.insert(0, record);
								}else if(value=="7"){
									//车位分期付款
									var record_1  = new needReceiveRecord({
										receivablesFunds:'一期款',
										businessFlag:'9',
										housingFundType:'38',
										receivedAmount:objectAmount[0].total
									});
									var record_2  = new needReceiveRecord({
										receivablesFunds:'二期款',
										businessFlag:'9',
										housingFundType:'39',
										receivedAmount:0
									});
									var record_3  = new needReceiveRecord({
										receivablesFunds:'三期款',
										businessFlag:'9',
										housingFundType:'40',
										receivedAmount:0
									});
									var record_4  = new needReceiveRecord({
										receivablesFunds:'四期款',
										businessFlag:'9',
										housingFundType:'41',
										receivedAmount:0
									});
									var record_5  = new needReceiveRecord({
										receivablesFunds:'五期款',
										businessFlag:'9',
										housingFundType:'42',
										receivedAmount:0
									});
									gridStore.insert(0, record_1);
									gridStore.insert(1, record_2);
									gridStore.insert(2, record_3);
									gridStore.insert(3, record_4);
									gridStore.insert(4, record_5);
								}else if(value=="8"){
									//车位按揭
									var record_1  = new needReceiveRecord({
										receivablesFunds:'首付款',
										businessFlag:'9',
										housingFundType:'35',
										receivedAmount:objectAmount[0].total
									});
									var record_2  = new needReceiveRecord({
										receivablesFunds:'银行按揭',
										businessFlag:'9',
										housingFundType:'36',
										receivedAmount:0
									});
									gridStore.insert(0, record_1);
									gridStore.insert(1, record_2);
								}
		                        //4、将临时对象的内容还原给原对象
		                        gridStoreTemporary.each(function(record) {
				    				gridStore.add(record);
				    			});
				    			//5、清空临时对象
				    			gridStoreTemporary.removeAll();
		                    }
		                }
		           }]
		        }, /*{
		        	items: [{
		            	xtype: 'combobox',
		                fieldLabel: '首付分期支付方式',
		                name:'decorationPaymentMethod',
		                id:'decorationPaymentMethod',
		                store: decorationMoneyStore,
		                queryMode: 'local',
		                displayField: 'name',
		                valueField: 'value',
		                value: signedInfoObj.decorationPaymentMethod,
		                listeners: {
		                    change: function(field,value) {
		                    	//由于没有找到效率高的解决方案
		                    	//（①全部删除对用户体验不好；②循环删除会下标越界；③js中对象之间的赋值是值引用；）
		                    	//因此暂时用以下方法处理删除首付分期的功能
		                    	//1、将内容赋值给临时对象
				    			gridStore.each(function(record) {   
				    			    if(record.get('receivablesFunds').indexOf('首付分期') < 0){
				    			    	gridStoreTemporary.add(record);
				    			    }  
				    			});  
				    			//2、删除原对象内容
				    			gridStore.removeAll();
				    			//3、将临时对象的内容还原给原对象
		                        gridStoreTemporary.each(function(record) {
				    				gridStore.add(record);
				    			});
				    			//4、清空临时对象
				    			gridStoreTemporary.removeAll();
				    			//5、生成首付分期数据
		                        if(value=="1"){ 
		                        	//一次性付款 
		                        	var record  = new needReceiveRecord({
		                        		receivablesFunds:'一次性付款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'26',
		                        		receivedAmount:0
		                        	});
		        				    gridStore.add(record);
		                        }else if(value=="2"){
		                        	//分期付款
		                        	var record_1  = new needReceiveRecord({
		                        		receivablesFunds:'一期款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'29',
		                        		receivedAmount:0
		                        	});
		                        	var record_2  = new needReceiveRecord({
		                        		receivablesFunds:'二期款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'30',
		                        		receivedAmount:0
		                        	});
		                        	var record_3  = new needReceiveRecord({
		                        		receivablesFunds:'三期款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'31',
		                        		receivedAmount:0
		                        	});
		                        	var record_4  = new needReceiveRecord({
		                        		receivablesFunds:'四期款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'32',
		                        		receivedAmount:0
		                        	});
		                        	var record_5  = new needReceiveRecord({
		                        		receivablesFunds:'五期款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'33',
		                        		receivedAmount:0
		                        	});
		                        	gridStore.add(record_1);
		                        	gridStore.add(record_2);
		                        	gridStore.add(record_3);
		                        	gridStore.add(record_4);
		                        	gridStore.add(record_5);
		                        }else if(value=="3"){
		                        	//商业按揭
		                        	var record_1  = new needReceiveRecord({
		                        		receivablesFunds:'首付款(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'27',
		                        		receivedAmount:0
		                        	});
		                        	var record_2  = new needReceiveRecord({
		                        		receivablesFunds:'银行按揭(首付分期)',
		                        		businessFlag:'19',
		                        		housingFundType:'28',
		                        		receivedAmount:0
		                        	});
		                        	gridStore.add(record_1);
		                        	gridStore.add(record_2);
		                        }
		                    }
		                }
		           }]
		        }*/]
	    };
		
    	Ext.define('needReceiveRecord', { 
            extend: 'Ext.data.Model', 
            fields: ["receivablesFunds","totalReceivablesAmount","receivedAmount","receivablesDate","orgName","agentName","businessFlag","housingFundType","loanYear",
            	"needReceivedAmount"]
	    });
    	//该对象用于更新支付方式时，临时存储gridStore
		var gridStoreTemporary = Ext.create('Ext.data.Store', {
			model:'needReceiveRecord'
		});
		var gridStore = Ext.create('Ext.data.Store', {
			model:'needReceiveRecord',
			remoteSort: false,
		    proxy: {
		        type: 'ajax',
		        url: contextPath+'/marketing/needReceiveRefund/findList',
		        reader: {  
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        },
		        actionMethods: {read: 'POST'},
	            extraParams:{
	            	relationId: signedInfoObj.id,
	            	businessType:'2'
	            }
		    },
		    autoLoad:true
		});
		
		/*gridStore.load({  
	        callback : function(record, options, success) {  
	        	Ext.getCmp("decorationMoney").setValue(true);
	        	for(var i = 0; i < record.length; i++){
	        		if(record[i].get('receivablesFunds') == '首付分期'){
	        			var item = Ext.getCmp("decorationMoney").items;
	        			item.each(function(row){
	        				row.setValue(true);
	        			});
	   			    }  
	        	}
	        }  
		});  */
		var columns = [{
			text : "款项",
			dataIndex : 'receivablesFunds',
			width:'10%'
		}, {
			text : "应收金额(元)",
			dataIndex : 'totalReceivablesAmount',
			width:'10%',
			editor: {
                xtype: 'numberfield',
                hideTrigger:true
            }
		},{
			text : "已收金额(元)",
			dataIndex : 'receivedAmount',
			width:'10%'
		},{
			text : "未收金额(元)",
			dataIndex : 'needReceivedAmount',
			width:'10%'
				/*,
			renderer: function(value,metadata,record){
				return record.raw.totalReceivablesAmount;
            }*/
		},{
			text : "应收日期",
			dataIndex : 'receivablesDate',
			width:'10%',
			editor: {
                xtype: 'datefield',
                format: 'Y-m-d',
                maxValue: receivable
            },
            renderer: function(value,metadata,record){  
                if(value!=null && value!=""){
                	return Ext.Date.format(new Date(value),'Y-m-d');
                }
                return value;
            }
		}, {
			text : "银行单位",
			dataIndex : 'orgName',
			width:'10%',
			editor: {
                xtype: 'textfield'
            }
		}, {
			text : "经办人",
			dataIndex : 'agentName',
			width:'10%',
			editor: {
                xtype: 'textfield'
            }
		},{
			text : "贷款年限",
			dataIndex : 'loanYear',
			width:'10%',
			editor: {
				xtype: 'numberfield',
				hideTrigger:true
			}
		}
//		,{
//        	text:'操作',
//        	xtype : 'actioncolumn',
//        	items:[{
//        		 iconCls:'icon-delete',
//        		 tooltip: '删除', 
//        		 handler: function(grid, rowIndex, colIndex) {
//        			 gridStore.removeAt(rowIndex);
//        		 }
//        	}]
//        }
		];
		var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		var row_7=Ext.create('Ext.grid.Panel', {
			id:'receivableAmountPanel',
			title:"应收款",
			minHeight:200,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
			store : gridStore,
			columns : columns,
			plugins: [cellEditing],
			listeners:{
	        	'edit':function(editor, e){
	        		var row = e.record;
	        		var totalReceivablesAmount = row.get("totalReceivablesAmount");
	        		if(totalReceivablesAmount != null){
	        			var receivedAmount = row.get("receivedAmount");
	        			row.set("needReceivedAmount",Number(totalReceivablesAmount)-Number(receivedAmount));
	        		}
	        		//计算合同金额，未收金额和首付分期
	        		//1、获取首付分期，并从合同金额、未收金额中减去
	        		var decorationMoneyAmount = Ext.getCmp("decorationMoneyAmount"); //首付分期
	        		var discountTotalAmount = Ext.getCmp("discountTotalAmount");	//合同金额
	        		discountTotalAmount.setValue(discountTotalAmount.getValue() - decorationMoneyAmount.getValue());
	        		var totalNeedReceivedAmount = Ext.getCmp("totalNeedReceivedAmount");	//未收金额
	        		totalNeedReceivedAmount.setValue(totalNeedReceivedAmount.getValue() - decorationMoneyAmount.getValue());
	        		//2、计算总首付分期金额
	        		var totalDecorationMoney = 0;
	        		gridStore.each(function(record) {   
	    			    if(record.get('receivablesFunds').indexOf('首付分期') >= 0){
	    			    	totalDecorationMoney = accAdd(totalDecorationMoney, record.get('totalReceivablesAmount'));
	    			    }  
	    			});  
	        		decorationMoneyAmount.setValue(totalDecorationMoney);
	        		//3、将首付分期加入合同金额、未收金额中
	        		discountTotalAmount.setValue(accAdd(discountTotalAmount.getValue(), decorationMoneyAmount.getValue()));
	        		totalNeedReceivedAmount.setValue(accAdd(totalNeedReceivedAmount.getValue(), decorationMoneyAmount.getValue()));
	        	},
	        	beforeedit : function(editor, e) {
	        		var row = e.record;
	        		var receivablesFunds = row.get("receivablesFunds");
	        		if(receivablesFunds.indexOf('首付分期') >= 0){
	        			//首付分期不需要设置收款周期
	        			e.column.getEditor().setMaxValue(false);
	        		}else if(e.field == 'receivablesDate'){
	                	//设置收款周期
	                	e.column.getEditor().setMaxValue(receivable);
	                }
	            }
			},
			tbar:[/*{text:'新增',iconCls:'icon-add',
				handler:function(){
				    Ext.define('Record', { 
			            extend: 'Ext.data.Model', 
				    }); 
				    var record  = new Record(); 
				    gridStore.insert(0, record);
				    cellEditing.startEditByPosition({
				        row: 0, 
				    	column: 1
				    });
			}
			}*/
			]
		});

		gridStoreJingJ = Ext.create('Ext.data.Store', {
			id:'agentGridStore',
		    fields: ["relationAgentid","proportionCommission"],
		    //是否在服务端排序 （true的话，在客户端就不能排序）
		    remoteSort: false,
		    proxy: {
				type: 'ajax',
		        url: contextPath+'/customer/transactionRelation/findTRList',
		        reader: {   //这里的reader为数据存储组织的地方，下面的配置是为json格式的数据，例如：[{"total":50,"rows":[{"a":"3","b":"4"}]}]
		            type: 'json', //返回数据类型为json格式
		            root: 'obj'
		        },
		        actionMethods: {read: 'POST'},
		        extraParams:{
		        	businessId: signedInfoObj.id,
		        	relationType: '6',
		        	merchantId: signedInfoObj.merchantId
		        }
		    }
		});
		gridStoreJingJ.load();
		
		
		var cellEditing_1 = Ext.create('Ext.grid.plugin.CellEditing', {
	        clicksToEdit: 1
	    });
		var agentColumns_1 = [{
			text: '经纪人',
            sortable : false,
            width:'20%',
            dataIndex: 'relationAgentid',
            name:'relationAgentid',
            editor:new Ext.form.field.ComboBox({
            	  queryMode:'local',
                  store:userIdStore,
                  valueField:'id',
                  displayField:'userName',
                  allowBlank:false,
                  blankText:'不能为空'  
            }),  
            renderer: function(value,metadata,record){  
                var index = userIdStore.find('id',parseInt(value));  
                if(index!=-1){  
                    return userIdStore.getAt(index).data.userName;  
                }else{
                	return value;
                }  
            }
        },{
			text : "分佣比例(%)",
			dataIndex: 'proportionCommission',
			id:'proportionCommission',
			name:'proportionCommission',
			width:'20%',
			editor: {
                xtype: 'textfield'
			}
        },{
        	text:'操作',
        	xtype : 'actioncolumn',
        	items:[{
        		 iconCls:'icon-delete',
        		 tooltip: '删除', 
        		 handler: function(grid, rowIndex, colIndex) {
        			 gridStoreJingJ.removeAt(rowIndex);
        			 if(gridStoreJingJ.getCount()<3){
   				    	Ext.getCmp("insertAgentBtn").setVisible(true);
   				     }
        		 }
        	 }]
        }];
		var agentPanel_1=Ext.create('Ext.grid.Panel', {
			id:'agentPanel',
			title:"经纪人",
			minHeight:150,
			columnLines: true,
	        viewConfig: {
	            stripeRows: true
	        },
	        store : gridStoreJingJ,
			columns : agentColumns_1,
			plugins: [cellEditing_1],
			tbar:[{text:'新增',iconCls:'icon-add',id:'insertAgentBtn',
				handler:function(){
					Ext.define('Record', { 
			            extend: 'Ext.data.Model' 
				    }); 
					var record  = new Record(); 
					gridStoreJingJ.insert(0, record);
					cellEditing.startEditByPosition({
				        row: 0, 
				    	column: 0
				    });
					if(Ext.getCmp("dealCategory").getValue() == '3'){
						if(gridStoreJingJ.getCount()>=3){
	  				    	Ext.getCmp("insertAgentBtn").setVisible(false);
	  				    }
					}else{
						if(gridStoreJingJ.getCount()>=1){
	  				    	Ext.getCmp("insertAgentBtn").setVisible(false);
	  				    }
					}
				}
			}]
		});
		
		//上传图片展示框
		var showImgPanel = Ext.create('Ext.Panel', {
	        width:600,
	       	height:120,
	        frame: true,
	        collapsible: false,
	      	autoScroll:true,
	      	bodyStyle: 'overflow-y:hidden; overflow-x:auto',
	        layout: "hbox"
	    });
		
		//收款附件表单
		var ajaxFileUploadForm = Ext.create("Ext.form.Panel", {
			border: false,
			items: [{
	            xtype: 'filefield',
	            fieldLabel: "合同扫描附件A",
	            buttonText: "合同扫描附件B",
	            name: "file",
	            layout: "hbox",
	            validator: function(value){
	            	if(value){
	            		if(!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG|BMP)$/.test(value)){
				      		return "合同扫描附件格式不正确!";
					    }else{
					    	return true;
					    }
	            	}else{
				    	return true;
				    }
				},
	            listeners: {
	        		change: function(file){
	        			var fileArrStr = me.getForm().findField("fileArr").getValue();
	        			if(null!=fileArrStr && fileArrStr!=""){
	        				var fileArrStrArray=fileArrStr.split("|");
	        				if(fileArrStrArray.length>9){
		        				Ext.Msg.alert('提示', '最多只能上传10张');
		        				return;
		        			}
	        			}
	        			
	        			var form = ajaxFileUploadForm.getForm();
		                if(form.isValid()){
			                form.submit({
			                    url: contextPath + '/common/file/extUploadFile?type=1',
			                    waitMsg: '附件上传中,请稍候...',
			                    success: function(form, action) {
			                    	var fileName = action.result.fileName;
			                    	var httpUrl = action.result.url;
			                    	var imgs="<a href='"+httpUrl+"' target='_blank'><img style='width: 80px; height: 90px;' title='"+fileName+"' src='"+httpUrl+"'/></a>";
			                    	var imgPanel = Ext.create("Ext.Panel", {
								        html: imgs
			                    	})
									showImgPanel.add(imgPanel);
									//添加隐藏字符串
									var fileArr = me.getForm().findField("fileArr").getValue();
									if(!fileArr){
										fileArr = httpUrl;
									}else{
										fileArr = fileArr + "|" + httpUrl;
									}
									me.getForm().findField("fileArr").setValue(fileArr);
									Ext.getCmp("certification").show();
				       			},
				       			failure: function(form, action){
		                        	Ext.Msg.alert('Failure', 'Your photo "' + action.result.fileName + '" has been uploaded.');
				       			}
			                });
		                }
	        		}
	        	}
	        },{
	        	xtype: "fieldcontainer",
	        	layout: "hbox",
	        	fieldLabel: "合同扫描附件C",
	        	id: "certification",
	        	name: "certification",
	        	hidden: true,
	        	items: [showImgPanel]
	        }]
		});
		
		
		var items=[row_1,row_2,row_3,row_4,row_5,row_6,row_7,
        //ajaxFileUploadForm, //注释合同扫描附件,采用下方组件附件
        /*{
        	xtype : 'hiddenfield',
	    	name: "fileArr",
        },*/{
        	xtype: 'textareafield',
            fieldLabel: '备注',
            anchor: '50%',
            name:'remark1',
            value: signedInfoObj.remark
        },{
        	xtype: 'datefield',
            fieldLabel: '<font style="color: #e90000;">*</font>签约日期',
            name:'signedDate',
            format: 'Y-m-d',
            value: new Date(),
            allowBlank:false,
            blankText:'不能为空'
        },{
        	xtype: 'combobox',
            fieldLabel: '成交类别',
            name:'dealCategory',
            id:'dealCategory',
            store: dealCategoryStore,
            queryMode: 'local',
            displayField: 'text',
            valueField: 'value',
            value:'2',
            listeners: {
                change: function(field,value) {
                	if(value=="3"){
                		if(gridStoreJingJ.getCount()<3){
                			Ext.getCmp("insertAgentBtn").setVisible(true);
                		}
                		Ext.getCmp("proportionCommission").setVisible(true);
            			Ext.getCmp("referenceName").hide();
            			Ext.getCmp("referenceButton").hide();
            			Ext.getCmp("referenceProportion").hide();
                	}else{
                		if(value=="1"){
                			Ext.getCmp("referenceName").show();
                			Ext.getCmp("referenceButton").show();
                			Ext.getCmp("referenceProportion").show();
                    		Ext.getCmp("proportionCommission").setVisible(false);
                		}else{
                			Ext.getCmp("referenceName").hide();
                			Ext.getCmp("referenceButton").hide();
                			Ext.getCmp("referenceProportion").hide();
                    		Ext.getCmp("proportionCommission").setVisible(true);
                		}
                		for(var i = 1; i < gridStoreJingJ.getCount(); i++){
                			gridStoreJingJ.removeAt(i);
                		}
//                		if(value=="2"){
//                			Ext.getCmp("proportionCommission").setVisible(false);
//                		}
                	}
                }
            }
        },{
        	layout: 'column',
        	items: [
            		{xtype:"textfield", id:'referenceId', name:"referenceId", hidden:true,
            			value: signedInfoObj.referenceId
            		},
            		{xtype:"textfield", id:'referenceName', fieldLabel:'推荐人姓名', hidden:true, name:"referenceName",
            			value: signedInfoObj.referenceName
            		},
            		{
	                	xtype:'button',
	                	text:'选择用户',
	                	id:'referenceButton',
	                	margin: 5,
	                	iconCls:'icon-search', 
	           		    handler: function() {
	           		    	var projectId = Ext.getCmp("projectId").getValue();
/*	           		 	    var selectWindow=Ext.create('component.user.selectWindow',{
	           		 			callbackFun: function (record) {
		           		 	  		var result=Ext.JSON.decode(record);
		           		 	  		Ext.getCmp("referenceName").setValue(result.userName);
		           		 	  		Ext.getCmp("referenceName").setDisabled(true);
		           		 	  		Ext.getCmp("referenceId").setValue(result.id);
	           		 	        }
	           		 	    	,projectId: projectId
	           		 	    });*/
	           		 	    var selectWindow=Ext.create('component.customer.selectWindow',{
	       		 			callbackFun: function (record) {
	   		 	          		var result=Ext.JSON.decode(record);
	   		 	          		var customerName=result.customerName;
	   		 	          		var customerId=result.id;
	   		 	          	    Ext.getCmp("referenceName").setValue(customerName);
           		 	  		    Ext.getCmp("referenceName").setDisabled(true);
           		 	  		    Ext.getCmp("referenceId").setValue(customerId);  
	       		 	        },
	       		 	        projectId: projectId,
	       		 	        resourcesCode:'menu_0006_0001'
	       		 	    });
           		 	    selectWindow.show();
	        		    }, hidden:true
	                },
            		{xtype:"numberfield",hideTrigger:true, id:'referenceProportion', fieldLabel:'推荐人比例', hidden:true,
	                	name:"referenceProportion",maxLength:3,regex:/^[1-9]\d*$/,
	                	value: signedInfoObj.referenceProportion
            		}
            ]
//        	xtype:'combobox',  
//            id:'userName',  
//            store: userIdStore,
//            displayField: "userName",           
//            valueField: "id",  
//            fieldLabel:'经纪人',  
//            width:200,
//			name:'agentId',
//			queryMode : 'local',  
//            listeners:{
//            	'change':function(value){
//            		if(value.lastValue){
//            			var index = userIdStore.find('id',value.lastValue);  
//            			if(index!=-1){  
////            				console.log(userIdStore.getAt(index));
////            				console.log(userIdStore.getAt(index).data);
////         		 	        return userIdStore.getAt(index).data.userName;
//         		 	        Ext.getCmp('userName').setValue(userIdStore.getAt(index).data.id);
//            			}
//            		}
//            	}
//            }
        },agentPanel_1];
		var initConfigg = {
				id:"subscribeInfoForm",
		        title:"签约信息",
		        minHeight:200,
		        fieldDefaults: {
		            labelAlign: 'left',
		            msgTarget: 'side',
		            margin: 5
		        },
		        items:items,
		        tbar:[{text:'抹零头',icon:contextPath+'/resources/ExtJSicons/tag/tag_blue_delete.png',handler:function(){
		        	Ext.tip.QuickTipManager.init();
		        	var zeroWindow = Ext.create("customer.signed.zero");
		        	var zeroForm = Ext.getCmp("zeroForm").getForm();
		        	var zeroValues={};
		        	var estatePanelForm =  Ext.getCmp("subscribeInfoForm").getForm();
		        	
		        	//ym修改start：只支持一次性抹掉
		        	//折前总价
		        	var totalPrice = estatePanelForm.findField('totalPrice').getValue();
		        	//折扣金额
		        	var discountAfterAmount = estatePanelForm.findField('discountAfterAmount').getValue();
		        	var resultHtAmount=totalPrice;
		        	if(null!=discountAfterAmount && discountAfterAmount!=""){
		        		resultHtAmount=parseFloat(totalPrice)-parseFloat(discountAfterAmount);
		        	}
		        	zeroValues.zeroMonry=resultHtAmount;
		        	//ym修改end：只支持一次性抹掉
		        	
		        	/*
		        	 * ym修改start：支持多次抹掉
		        	 * var estatePanelFormAmount = estatePanelForm.findField('discountTotalAmount').getValue();
		        	 * zeroValues.zeroMonry=estatePanelFormAmount;
		        	 *ym修改end：支持多次抹掉
		        	*/
		        	
		        	
		        	var estatePanelForm = Ext.getCmp("estatePanel").getForm();
		        	var windowRoomId = estatePanelForm.findField("id").getValue();
		        	
		        	
		        	Ext.Ajax.request({
						url:contextPath+'/estate/projectRoom/findPriceByRoomId',
			    		params:{
			    			"roomId":windowRoomId,
			    			"payDepositId":payDepositId,
			    			"subscribeId":subscribeId
			    		},
			    		callback: function (options, success, response) {
			    			 var resp = Ext.decode(response.responseText);
			    			 var html = "";
			    			 if(resp.obj!=null){
			    				 html="最多可抹零"+resp.obj+"元";
			    			 }else{
			    				 html="没有最多限制!";
			    			 }
			    			 zeroValues.discountRateDisplayZeroHidden=resp.obj;
			    			 zeroValues.discountRateDisplayZero=html;
					         zeroForm.setValues(zeroValues);
			    		}
					});
		        	zeroWindow.show();
		        }}]
		        
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
		Ext.getCmp("dealCategory").setValue(signedInfoObj.dealCategory);
	}
});

//抹零头窗口

Ext.define('customer.signed.zero.panel',{
	extend:'Ext.form.Panel',
	initComponent:function(){
		var items = {
				
				width:330,
				height:130,
				items:[{
					xtype : 'displayfield',
					fieldLabel : '合同金额(元)',
					name:'zeroMonry',
					readOnly:true
		            
				},{
					xtype : 'numberfield',
					fieldLabel : '抹零金额(元)',
					name:'clearZero',
					hideTrigger:true,
					minValue: 0,
					listeners:{
						'change':function(val){
							var zeroForm = Ext.getCmp("zeroForm").getForm();
							var zeroMonry =  zeroForm.findField("zeroMonry").getValue(); 
							var vals = val.getValue();
							if(vals==null||vals==""){
								vals=0;	
							}
							
							zeroForm.findField('discountRateDisplayBack').setValue(parseFloat(zeroMonry)-parseFloat(vals));
						}
					}
				},{
            		xtype:'displayfield',
            		hideLabel:true,
            		name:'discountRateDisplayZero'
            	},{
            		xtype: 'hiddenfield',
	                name:'discountRateDisplayZeroHidden'
            	},{
					xtype : 'displayfield',
					fieldLabel : '抹零后(元)',
					name:'discountRateDisplayBack'
				}]	
		};
		
		var initConfigg = {
				 id:'zeroForm',
				 items:items,
				 collapsed: false ,
				 collapsible: false
		};
		Ext.apply(this,initConfigg);
		this.callParent(arguments);
		
	}
});
var haveAmount = 0;
Ext.define('customer.signed.zero',{
	extend:'Ext.window.Window',
	initComponent:function(){
		var zeroPanel=Ext.create("customer.signed.zero.panel");
		var me = this;
		
		var defaultConfigg = {
				buttonAlign:'center',
				title:'抹零头',
				  plain: true,
			        modal: true,
				defaults: {  
		            split: true,    //有分割线  
		            collapsible: true  //可以折叠
		        },
				items:[zeroPanel],
				buttons:[
				         {xtype: "button",text: "保存",handler: function(){
				        		var zeroForm = Ext.getCmp("zeroForm").getForm();
				        		var clearZero =  zeroForm.findField("clearZero").getValue(); 
				        		var maxClearZero = zeroForm.findField("discountRateDisplayZeroHidden").getValue(); 
				        		var zeroMonry = zeroForm.findField("zeroMonry").getValue(); 
				        		if(clearZero==null||clearZero==""){
				        			clearZero=0;
				        		}
				        		var flagStatus = true;
				        		if(maxClearZero!=null&&maxClearZero!=""){
				        			if(parseFloat(clearZero)>parseFloat(maxClearZero)){
				        				Ext.Msg.alert('提示', '已超过最多抹零限制!');
				        				flagStatus=false;
				        			}
				        		}
				        	
				        		if(flagStatus){
				        			var estatePanelForm =  Ext.getCmp("subscribeInfoForm").getForm();
				        			var discountRateDisplayBack= zeroForm.findField("discountRateDisplayBack").getValue(); 
				        			var estatePanelFormValue = {};
				        			var lkFormValue = estatePanelForm.findField("hetongPayPrice").getValue();
				        			var lkParseValue = 0;
				        			if(lkFormValue!=null&&lkFormValue!=""){
				        				lkParseValue=parseFloat(lkFormValue);
				        			}
				        		
				        			//haveAmount+=clearZero;
				        			if(maxClearZero!=null&&maxClearZero!=""){
						        		if(haveAmount>maxClearZero){
						        			Ext.Msg.alert('提示', '已超过最多抹零限制!');
						        			haveAmount=haveAmount-clearZero;
						        			return;
						        		}	
				        			}
				        			
				        			estatePanelFormValue.totalNeedReceivedAmount=parseFloat(discountRateDisplayBack)-lkParseValue;
				        			estatePanelFormValue.discountTotalAmount=discountRateDisplayBack;
				        			estatePanelForm.setValues(estatePanelFormValue);
				        			me.close();
				        		}
				        	   
				        		
				         }},{xtype: "button",text: "取消",handler: function(){
				        	me.close();
				         }}
				]
		};
		Ext.apply(this,defaultConfigg);
		this.callParent(arguments);
		
	}
});
Ext.define('customer.signed.addPanel',{
	extend : 'Ext.form.Panel',
	initComponent:function(){
		var estatePanel= Ext.create("customer.signed.add.estatePanel");
		var customerPanel= Ext.create("customer.signed.add.customerPanel");
		var subscribePanel= Ext.create("customer.signed.add.subscribePanel");
		var fileAttachment = Ext.create('component.file.attachment',{
		    objectId: signedInfoObj.id,
		    imageType: "3",
		    contextPath:contextPath,
		    //显示上传按钮
		    showBtn: "T",
		    //显示上传图片删除按钮
		    showDelBtn: "T"
		});
	var submitFun=function(startProcess){
		
		//房源信息
       	var estateForm=estatePanel.getForm();
       	var signedId = estateForm.findField("signedId").getValue();
       	var roomId=estateForm.findField("id").getValue();
       	var billingArea=estateForm.findField("billingArea").getValue();
    	var calculateUnitPrice=estateForm.findField("calculateUnitPrice").getValue();
    	var totalPrice=estateForm.findField("totalPrice").getValue();
      	if(roomId=="" || null==roomId){
      		Ext.Msg.alert('提示', '请选择房源');
          	return;
     	}
      	if(totalPrice=="" || null==totalPrice){
      		Ext.Msg.alert('提示', '房源折前总价未设置');
         	return;
      	}
       	 //客户信息
      	var customerForm=customerPanel.getForm();
      	var customerId=customerForm.findField("id").getValue();
       	if(customerId=="" || null==customerId){
       		Ext.Msg.alert('提示', '请选择客源');
       		return;
     	}
		if(!customerForm.isValid()){
			return false;
		}

   	 	var familyMemberGridStore=customerPanel.getComponent("familyMemberGridPanel").getStore();
   	 	var jsonArray=[];
		var recordsCount=familyMemberGridStore.getCount();
		if(recordsCount>0){
			for(var i=0;i<recordsCount;i++){
				var documentNumber = familyMemberGridStore.getAt(i).data.documentNumber;
   				if(documentNumber==null||documentNumber==""){
					Ext.Msg.alert('提示', '请填写共同购房者证件号码!');
					return;
				}else{
					//验证手机号码的正确性
					var userPhone = familyMemberGridStore.getAt(i).data.mobile;
					if(userPhone!=null&&userPhone!=""){
//						var regTel = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/;
//						if(!regTel.test(userPhone)){
//							Ext.Msg.alert('提示', '请输入正确的手机号码!');
//							return;
//						}
						Ext.Ajax.request({
							url: contextPath+'/common/mobile/verifyingMobile',
							params: {
								mobile: userPhone,
							},
							method: 'POST',
							async: false,
							success: function(response){
								var text = Ext.decode(response.responseText);
								if(text.result=="1"){
									if(text.flag != "1"){
										Ext.Msg.alert('提示', '请输入正确的手机号码!');
		    							return;
									}
								}
							}
						 });
					}
					jsonArray.push(Ext.JSON.encode(familyMemberGridStore.getAt(i).data));
				}
			}
		}
		 
		 
		var receivableAmountStore=subscribePanel.getComponent("receivableAmountPanel").getStore();	
   	    var receivableAmountArray=[];
   	    var receivableAmountCount=receivableAmountStore.getCount();
	    if(receivableAmountCount>0){
		  for(var i=0;i<receivableAmountCount;i++){
			  var rowData=receivableAmountStore.getAt(i).data;
			  //应收日期
			  var receivablesDate=rowData.receivablesDate;
			  //应收金额
			  var totalReceivablesAmount=rowData.totalReceivablesAmount;
			  if(null!=totalReceivablesAmount && totalReceivablesAmount!=""){
				  if(null==receivablesDate || receivablesDate==""){
					  Ext.Msg.alert('提示', '请填写应收日期！');
					  return;
				  }
			  }
			  if(null!=receivablesDate && receivablesDate!=""){
				  if(null==totalReceivablesAmount || totalReceivablesAmount==""){
					  Ext.Msg.alert('提示', '请填写应收金额！');
					  return;
				  }
			  }
			  if(null!=receivablesDate && receivablesDate!="" && null!=totalReceivablesAmount && totalReceivablesAmount!=""){
				  receivableAmountArray.push(Ext.JSON.encode(rowData));
			  }
    	  }
	    }
	    if(receivableAmountArray.length<=0){
	    	Ext.Msg.alert('提示', '请填写应收款项！');
			return;
	    }

       	 //认购信息
       	 var subscribe=subscribePanel.getForm().getValues();
       	 var signedForm=subscribePanel.getForm();
		    			    
       	 var agentGridStore=subscribePanel.getComponent("agentPanel").getStore();
     	 var jsonArrayAgent=[];
     	 var number = 0;
  		 var recordsCount=agentGridStore.getCount();
  		 if(recordsCount>0){
  			 for(var i=0;i<recordsCount;i++){
  				 var reg = /^\d+(?:\.\d{1,2})?$/;
  				 var proportionCommission = agentGridStore.getAt(i).data.proportionCommission;
  				 if(reg.test(proportionCommission)==false){
  					 Ext.Msg.alert('提示', '分佣比例请输入数字!');
					 return;
  				 }else{
  					 number=number+parseFloat(proportionCommission);
  					 jsonArrayAgent.push(Ext.JSON.encode(agentGridStore.getAt(i).data));
  				}
  	    	}
  		 }else{
  			 Ext.Msg.alert('提示', '请选择经纪人');
  			 return;
  		 }
  		 if(number>100&&subscribe['dealCategory'] == 3){
  			 Ext.Msg.alert('提示', '分佣比例累加不能超过100%!');
  			 return;
  		 }
  		 if(number<100&&subscribe['dealCategory'] == 3){
  			Ext.Msg.alert('提示', '分佣比例累加要等于100%!');
 			 return;
  		 }

  		 var referenceName=signedForm.findField("referenceName").getValue();
  		 var referenceProportion=signedForm.findField("referenceProportion").getValue();
  		 var referenceId=signedForm.findField("referenceId").getValue();
  		 if(subscribe['dealCategory'] == 1){
           	 if(referenceName=="" || null==referenceName){
           		 Ext.Msg.alert('提示', '请填写推荐人姓名');
               	 return;
           	 }
           	 if(referenceProportion=="" || null==referenceProportion){
           		 /*Ext.Msg.alert('提示', '请填写推荐人比例');
               	 return;*/
               	referenceProportion=""
           	 }

       		var ionum = number+parseInt(subscribe['referenceProportion']);
       		if(ionum>100){
           		Ext.Msg.alert('提示', '推荐人比例和分佣比例总和不能超过100%');
           		return;
       		}
       		if(ionum<100){
           		Ext.Msg.alert('提示', '推荐人比例和分佣比例总和不能小于100%');
           		return;
       		}
		}else{
			//当编辑时,如果不是推荐成交类型,需将推荐相关信息设为空
			referenceName = "";
			referenceProportion = "";
			referenceId = "";
		}
       	for(var i = 0; i < recordsCount; i++){
      		var jsonAgent = eval("(" + jsonArrayAgent[i] + ")");
  			if(jsonAgent.relationAgentid == ""){
          		Ext.Msg.alert('提示', '请选择经纪人');
          		return;
          	}
  			if(subscribe['dealCategory'] == 1){
  				if(jsonAgent.proportionCommission == undefined 
      					|| jsonAgent.proportionCommission == ""){
              		Ext.Msg.alert('提示', '请填写分佣比例');
              		return;
              	}
  			}
  			if(subscribe['dealCategory'] == 3){
  				if(jsonAgent.proportionCommission == undefined 
      					|| jsonAgent.proportionCommission == ""){
              		Ext.Msg.alert('提示', '请填写分佣比例');
              		return;
              	}
  			}
  		 }
   	
        //判断证件类型是否做了修改
        var peDocumentType = customerForm.findField("peDocumentTypeName").getValue();
        if(isNaN(peDocumentType)){
       	 	peDocumentType = "";
        }
   	
        var params={};
   	 	//房源信息
   	 	params.id = signedId;
   	 	params.roomId=roomId;
       	params.calculateArea=billingArea;
       	params.conversionPrice=calculateUnitPrice;
       	params.lumpsumPrice=totalPrice;
       	//客户信息
       	params.floorType=subscribe['floorType'];
       	params.discountAfterPrice=subscribe['discountAfterPrice'];
       	params.customerId=customerId;
       	params.peDocumentTypeName = peDocumentType;
      	params.peDocumentNumber = customerForm.findField("peDocumentNumber").getValue();
        //验证证件号是否正确
 		var ver = verifyIDNumber(customerForm.findField("peDocumentTypeName").getRawValue(), params.peDocumentNumber);
    	if(ver == false){
    		return false;
    	}
      	params.peContactAddress = customerForm.findField("peContactAddress").getValue();
      	params.pePostcode = customerForm.findField("pePostcode").getValue();
      	params.customerName = customerForm.findField("customerName").getValue();
       	//签约编号
       	params.signCode=subscribe['signedCode'];
       	//签约日期
       	params.didTime=subscribe['signedDate'];
       	//合同类型：正常合同
       	params.contactType=subscribe['contactType'];
       	//折扣比例
       	params.discountRate=signedForm.findField("discountRate").getValue();
       	//折扣金额
       	params.discountAmount=subscribe['discountAfterAmount'];
       	//折扣说明
       	params.discountNote=subscribe['discountNote'];
       	//成交类型
       	params.dealCategory=subscribe['dealCategory'];
       	//付款方式
       	params.paymentMethod=subscribe['paymentMethod'];
       	//首付分期付款方式
       	params.decorationPaymentMethod=subscribe['decorationPaymentMethod'];
       	//首付分期金额
        params.decorationMoney=signedForm.findField("decorationMoneyAmount").getValue();
       	//签约合同金额（数据库保存的合同金额不包含首付分期，因此取房款金额，以免影响后续逻辑）
       	//params.signAmount=signedForm.findField("discountTotalAmount").getValue();
      	params.signAmount=signedForm.findField("roomTotalAmount").getValue();
       	//签约合同单价
       	params.signPrice=signedForm.findField("discountAmount").getValue();	 
       	//合同剩余金额
       	params.receivableAmount=signedForm.findField("totalNeedReceivedAmount").getValue();
       	if(params.receivableAmount && params.receivableAmount == "NaN"){
       		params.receivableAmount = 0;
       	}
       	//备注
       	params.remark=subscribe['remark1'];
       	//经纪人
       	var discountRateHidden=subscribe['discountRateHidden'];
       	var discountRate=params.discountRate;
         
      	if(subscribe['floorType']=="1"){
      		//价格方案是折扣的时候
      		if(parseFloat(discountRate)<parseFloat(discountRateHidden)){
      			params.discountApproval='1';
          	}else{
          		params.discountApproval='0'; 
          	}
      		//console.log("折后折扣率/低价和价格方案设置对比："+parseFloat(discountRate)+":"+parseFloat(discountRateHidden));
    	}else if(subscribe['floorType']=="0"){
    		//如果折后金额低于底价时 要发起折扣审批
      		if(parseFloat(subscribe['discountAfterPrice'])<parseFloat(discountRateHidden)){
          		params.discountApproval='1';
         	}else{
          		params.discountApproval='0'; 
          	}
      		//console.log("折后折扣率/低价和价格方案设置对比："+parseFloat(subscribe['discountAfterPrice'])+":"+parseFloat(discountRateHidden));
     	}else{
      		Ext.Msg.alert('提示', '价格方案低价方式设置错误');
      		return; 
    	}
      	if(null==params.discountApproval || params.discountApproval==""){
       		Ext.Msg.alert('提示', '是否折扣审批参数错误');
       		return;
      	}
      	//console.log("是否发起折扣审批(0否：1是)："+params.discountApproval);
       	params.familyMember=jsonArray;
       	params.needReceive=receivableAmountArray;
       	var extraInformation={
	       	depositAmount:payAepositAmount,
	       	subscribeAmount:subscribeAmount,
	       	paymentDetails:receivableAmountArray 
       	}
        params.extraInformation=extraInformation;
        
       	params.subscribeId=subscribeId;
       	params.payDepositId=payDepositId;
       	params.payDepositMoney=payAepositAmount;
        params.subscribeAmount=subscribeAmount;
        params.subscribeCode=subscribeCode;
        params.payDepositCode=payDepositCode;
        params.agents = jsonArrayAgent;
        params.referenceName = referenceName;
        params.referenceProportion = referenceProportion;
        params.referenceId = referenceId;
       	if(params.signAmount=="" || null==params.signAmount){
      		Ext.Msg.alert('提示', '签约合同金额错误');
        	return;
      	}
       	if(params.paymentMethod=="" || null==params.paymentMethod){
       		Ext.Msg.alert('提示', '付款方式必选');
        	return;
    	}
       	if(params.didTime=="" || null==params.didTime){
    		Ext.Msg.alert('提示', '签约日期不能为空');
        	return;
    	}
       	
       	//验证所有应收款 相加 等于合同未收金额
	    var validArray=receivableAmountArray;
	    var validPrice = 0;
	    var decorationMoney = 0;
	    if(validArray!=null&&validArray.length>0){
	    	for(var i=0;i<validArray.length;i++){
	    		var objectValid = JSON.parse(validArray[i]);
	    		if(objectValid.receivablesDate==""||objectValid.receivablesDate==null){
	    			   Ext.Msg.alert('提示', '应收日期不能为空!');
	    			   return;
	    		}
	    		//合同金额不包含首付分期
    			if(objectValid.totalReceivablesAmount!=""&&objectValid.totalReceivablesAmount!=null){
	    			//validPrice+=Number(objectValid.totalReceivablesAmount);
	    			//2018-03-15 增加js加法精确计算
	    			validPrice = accAdd(validPrice, Number(objectValid.totalReceivablesAmount))
	    		}
	    	}
	    }	 
	    var discountTotalAmountVaild=signedForm.findField("discountTotalAmount").getValue();
		discountTotalAmountVaild = Ext.util.Format.number(discountTotalAmountVaild, '0.00');
	    if(validPrice!=discountTotalAmountVaild){
	    	Ext.Msg.alert('提示', '应收金额相加要等于合同金额!');
	     	return;
	    } 
       	
		var agentGridStore=subscribePanel.getComponent("agentPanel").getStore();
 	 	var jsonArrayAgent=[];
	 	var recordsCount=agentGridStore.getCount();
	 	if(recordsCount>0){
			for(var i=0;i<recordsCount;i++){
				jsonArrayAgent.push(Ext.JSON.encode(agentGridStore.getAt(i).data));
	    	}
	 	}else{
			Ext.Msg.alert('提示', '请选择经纪人');
	  		return;
	 	} 
	 	//签约凭证
//	 	var fileArr=signedForm.findField("fileArr").getValue();
//	 	params.fileArr=fileArr;
	 	
	 	var fileUrlArr =fileAttachment.getFileArrs();
	 	params.fileUrlArr=fileUrlArr;
	 	params.imageType = "3";
	 	var resultJson=Ext.JSON.encode(params);
       	 if(startProcess){
       		 Ext.getCmp("save_button").setVisible(false);
       	 }
       	 Ext.Msg.wait("签约提交中，请等待……","");
       	 Ext.Ajax.request({
        	    url: contextPath+'/customer/signed/add',
        	    params: {
        	    	params: resultJson,
        	    	startProcess:startProcess,
        	    	roomId:roomId,
        	    	token: token //防重复提交
        	    },
        	    method: 'POST',
        	    success: function(response){
        	    	Ext.Msg.hide();
        	    	var text = "";
        	    	if(response.responseText){
        	    		text = Ext.decode(response.responseText);
        	    	}
        	        if(text.res=="1"){
        	        	Ext.getCmp("signedId").setValue(text.obj);
        	        	fileAttachment.deleteBtnHidden();
        	        	Ext.Msg.alert('提示', text.resMsg);
        	        	Ext.MessageBox.alert("系统提示", text.resMsg, function(but) {  
    	        		  	 var tabKey = "sub_to_sig_"+signedInfoObj.id;
			        		 var tabSigned = "sig_"+text.obj;
			        		 var url = "/customer/signed/toView?id="+text.obj+"&returnUrl=,marketing,pin,index";
			        		 parent.openMenu("0",tabSigned,"","签约详情",url);	
			        		 parent.TabControlRemove(tabKey);
		                });  
        	        }else if(text.res=="100"){
        	        	Ext.getCmp("save_button").setVisible(true);
        	        	token = text.obj;
        	        	Ext.Msg.alert('提示', '权限不足！');
        	        }else{
        	        	Ext.getCmp("save_button").setVisible(true);
        	        	token = text.obj;
        	        	Ext.Msg.alert('提示', '签约失败！原因：'+text.resMsg);
        	        }
        	    }
        	});
		};
	
		var defaultConfigg = {
			buttonAlign:'center',
			defaults: {  
	            split: true,    //有分割线  
	            collapsible: true  //可以折叠
	        },
	        renderTo:Ext.getBody(),
			items:[estatePanel,customerPanel,subscribePanel,fileAttachment],
			buttons:[
			         {xtype: "button",text: "保存",iconCls:'icon-save',handler: function(){
			        	 submitFun(false); 
			         }},
			         {xtype: "button",id:'save_button',text: "提交审核",handler: function(){
			        	 submitFun(true);
			         }},{xtype: "button",text: "返回",handler: function(){
			        	 var tabKey = "sub_to_sig_"+signedInfoObj.id;
		        		 parent.TabControlRemove(tabKey);
			         }}
			]
		};
		Ext.apply(this,defaultConfigg);
		this.callParent(arguments);
	}
});


//获取房间类型
function loadRoomType(roomId, projectId){
	Ext.Ajax.request({
		method: 'POST',
	    url: contextPath+'/estate/projectRoom/view',
	    params: {
	    	"id": roomId
	    },
	    success: function(response){
	    	var data = Ext.decode(response.responseText);
			if(data.res == "0"){
				return false;
			}
			if(data.obj.industMark == null){
				return false;
			}
			//获取项目参数设置
			loadProjectParameter(data.obj.industMark, projectId)
		}
	});
}

//加法精确精算
function accAdd(arg1,arg2){ 
	var r1,r2,m; 
	try{
		r1=arg1.toString().split(".")[1].length
	}catch(e){
		r1=0
	} 
	try{
		r2=arg2.toString().split(".")[1].length
	}catch(e){
		r2=0
	} 
	m=Math.pow(10,Math.max(r1,r2)) 
	return (arg1*m+arg2*m)/m 
} 
Number.prototype.add = function (arg){ 
	return accAdd(arg,this); 
}

//获取房间类型
function loadRoomType(roomId, projectId){
	Ext.Ajax.request({
		method: 'POST',
	    url: contextPath+'/estate/projectRoom/view',
	    params: {
	    	"id": roomId
	    },
	    success: function(response){
	    	var data = Ext.decode(response.responseText);
			if(data.res == "0"){
				return false;
			}
			if(data.obj.industMark == null){
				return false;
			}
			//获取项目参数设置
			loadProjectParameter(data.obj.industMark, projectId)
		}
	});
}

//获取项目参数中的收款周期
function loadProjectParameter(typeId, projectId){
	Ext.Ajax.request({
		method: 'POST',
	    url: contextPath+'/estate/projectParameter/getProjectParameter',
	    params: {
	    	"typeId": typeId,
			"projectId": projectId,
			"cycleType": "receivable"
	    },
	    success: function(response){
	    	var data = Ext.decode(response.responseText);
			if(data.res == "0"){
				return false;
			}
			if(data.obj == null){
				return false;
			}
			receivable = addDate(new Date(), Number(data.obj.cycleValue));
		}
	});
}
//校验证件号码
function verifyIDNumber(type, code){
	var url = "";
	if(type == '身份证'){
		url = "verifyIDCard";
	} else if(type == '营业执照'){
		url = "verifyBusinessLicense";
	} else {
		return true;
	}
	var flag = true;
	Ext.Ajax.request({
		url: contextPath+'/common/idNumber/'+url,
		params: {
			"code": code,
		},
		method: 'POST',
		async: false,
		success: function(response){
			var text = Ext.decode(response.responseText);
			if(text == false){
				Ext.MessageBox.alert('提示', '请输入正确的'+type);
				flag = false;
			}
		}
	});
	return flag;
}
